<?php
// +----------------------------------------------------------------------
// | Description: Api基础类，验证权限 (将前后台请求分流)
// +----------------------------------------------------------------------
// | Author: dongpeng
// +----------------------------------------------------------------------

namespace app\common\controller;

use app\common\adapter\AuthAdapter;
use think\Db;
use think\Request;

class ApiCommon extends Common
{
    protected $isClient = false;      // 该访问是否来自客户端
    public function _initialize()
    {
        parent::_initialize();
        $this -> back();            // 如果后台已经登录  则直接获取接口访问权限
        if(!$GLOBALS['userInfo']){  // 如果后台没有登录
            $this -> front();       // 检查客户端是否也登录了
        }
    }

    /**
     * 客户端权限认证
     * @return void
     */
    public function front()
    {
        $this -> abort(session('clientInfo'), '没有权限', 403);
        $this -> isClient = true;     // 权限验证通过 标注该访问为客户端
    }

    public function back()
    {
        /*获取头部信息*/
        $header = Request::instance()->header();
        $authKey = $header['authkey'];
        $sessionId = $header['sessionid'];
        $cache = cache('Auth_' . $authKey);
        // 校验sessionid和authKey
        $this->abort(!empty($sessionId) && !empty($authKey) && !empty($cache), '登录已失效', 101);
        // 检查账号有效性
        $userInfo = $cache['userInfo'];
        $map['id'] = $userInfo['id'];
        $map['status'] = 1;
        $this->abort(Db::name('admin_user')->where($map)->value('id'), '账号已被删除或禁用', 102);
        // 更新缓存
        $this->MylogData['uid'] = $userInfo['id'];
        cache('Auth_' . $authKey, $cache, config('LOGIN_SESSION_VALID'));
        $authAdapter = new AuthAdapter($authKey);
        $request = Request::instance();
        $ruleName = $request->module() . '-' . $request->controller() . '-' . $request->action();
        $this->abort($authAdapter->checkLogin($ruleName, $cache['userInfo']['id']), '权限不足', 103);
        $GLOBALS['userInfo'] = $userInfo;
    }
}
